package com.qf.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebFilter({
        "*.html",
        "/card/*",
        "/cc/*",
        "/person/*",
        "/proServlet/*",
        "/user/*"
})
public class Filter005_LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;

        //对一些不需要做登录验证的资源进行放行：登录相关、注册相关、js、css、images..
        //① 得知道当前访问的具体资源是什么

        /*
            http://localhost:8080/cookie/user?action=findOne&id=1

            URL: 中华人民共和国  http://localhost:8080/cookie/user
            URI: 共和国   /cookie/user
            QueryString:   action=findOne&id=1
         */
        String uri = req.getRequestURI();
        //② 判断是否是登录相关、注册相关
        if (uri!=null &&
                (uri.endsWith("login.html")
                        || uri.endsWith("register.html")
                )){
            //放行
            filterChain.doFilter(req,resp);
            return;
        }

        String action = req.getParameter("action");
        if ("login".equals(action)
                || "register".equals(action)
        ){
            //放行
            filterChain.doFilter(req,resp);
            return;
        }
        //做是否登录的判断
        Object id = req.getSession().getAttribute("id");
        if (id == null){
            //没有登录
            resp.sendRedirect(req.getContextPath() + "/login.html");
        }

        //登录了-放行
        filterChain.doFilter(req,resp);
    }

    @Override
    public void destroy() {

    }

}
